package com.xbongbong.saas.analytical.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.enums.errorcodes.CustomerCommunicateErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SupplierErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.analytical.SaasValidateAnalyticalService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.help.SaveFormatHelp;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author 吴峰
 * @date 2021/07/15 17:15
 */
@Service("supplierCommunicateAnalyticalServiceImpl")
public class SupplierCommunicateValidateAnalyticalServiceImpl implements SaasValidateAnalyticalService {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(SupplierCommunicateValidateAnalyticalServiceImpl.class);
    
    @Resource
    private EsHelper esHelper;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private UserModel userModel;

    @Override
    public List<Integer> type() {
        return Arrays.asList(XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getCode());
    }

    @Override
    public void analyticalData(ValidateDataDTO validateDataDTO) throws XbbException {
        beforeSave(validateDataDTO);
    }
    
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        try {
            String corpid = validateDataDTO.getCorpid();
            String userId = validateDataDTO.getUserId();
            JSONObject data = validateDataDTO.getData();
            Long dataId = validateDataDTO.getDataId();
            SaveFormatHelp.formatLinkBusiness4Save(data, SupplierCommunicateEnum.SUPPLIER_ID.getAttr(), SupplierCommunicateEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(), SupplierCommunicateEnum.SUPPLIER_ID.getFieldType());
            SaveFormatHelp.formatLinkBusiness4Save(data, SupplierCommunicateEnum.SUPPLIER_CONTACT.getAttr(), SupplierCommunicateEnum.SUPPLIER_CONTACT_NAME_LINK_TEXT.getAttr(), SupplierCommunicateEnum.SUPPLIER_CONTACT.getFieldType());
            SaveFormatHelp.formatCommunicateBusiness4Save(data, SupplierCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(), SupplierCommunicateEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(), SupplierCommunicateEnum.COMMUNICATE_BUSINESS_LINK_TEXT.getAttr());
            Long communicateTime = FastJsonHelper.getLongOrDefaultFromFormData(data, SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr(), 0L);
            if (Objects.equals(communicateTime, BasicConstant.ZERO)) {
                throw new XbbException(CustomerCommunicateErrorCodeEnum.API_ERROR_206004);
            }
            if (communicateTime > DateTimeUtil.getInt()){
                throw new XbbException(CustomerCommunicateErrorCodeEnum.API_ERROR_206008);
            }

            Long supplierId = FastJsonHelper.getLongFromFormData(data, SupplierCommunicateEnum.SUPPLIER_ID.getAttr());
            JSONArray contactArr = FastJsonHelper.getJsonArrFromFormData(data, SupplierCommunicateEnum.SUPPLIER_CONTACT.getAttr());
            if (Objects.nonNull(contactArr)) {
                List<Long> contactIds = contactArr.toJavaList(Long.class);
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + ".keyword", corpid));
                boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, contactIds));
                boolQueryBuilder.filter(termQuery("data."+ SupplierContactEnum.SUPPLIER_ID.getAttr() + ".keyword", Objects.toString(supplierId)));
                boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.DATA_ID);
                List scroll = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT, boolQueryBuilder, PaasFormDataEntity.class, fieldList);
                if (!Objects.equals(contactIds.size(), scroll.size())) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NOT_RELY_BUINESS, SupplierCommunicateEnum.SUPPLIER_CONTACT.getAttrName());
                }
            }
            SupplierEntityExt supplierEntityExt = supplierModel.getByKey(supplierId, corpid);
            if (supplierEntityExt == null) {
                throw new XbbException(SupplierErrorCodeEnum.API_ERROR_233017);
            }
            if (dataId == null || dataId == 0) {
                data.put(SupplierCommunicateEnum.AUTO_GEN.getAttr(), 0);
                UserEntity userEntity = userModel.getByKey(userId, corpid);
                data.put(SupplierCommunicateEnum.USER_ID.getAttr(), userEntity.getUserId());
                data.put(SupplierCommunicateEnum.USER_NAME.getAttr(), userEntity.getName());
                data.put(SupplierCommunicateEnum.USER_AVATAR.getAttr(), Collections.singletonList(userEntity.getAvatar()));
            }

            validateDataDTO.setData(data);
        } catch (XbbException e) {
            throw e;
        }  catch (Exception e) {
            LOGGER.error("SupplierCommunicateValidateAnalyticalServiceImpl.beforeSave error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
